package driving;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import com.g2room.driving.generate.to.ArticleTo;
import com.g2room.driving.util.DbUtil;
import com.g2room.driving.util.ImageUtil;

public class HandleImages {
	static Map<String, String> oldImgMap = getOldImgs();
	public static void main(String[] args) {
//		handlImgs();
		handlThumbImgs();
		
//		updateContentImgSrc();
//		DbUtil.closeConn();
	}
	
	public static void updateContentImgSrc() {
		try {
			int i =0;
			Connection connection = DbUtil.getQgshConn();
			Statement statement = connection.createStatement();
			PreparedStatement updateSt = connection.prepareStatement("update d_article_grap set content=replace(content,?,?) where id=?");
			PreparedStatement updateThumbSt = connection.prepareStatement("update d_article_grap set thumb=replace(thumb,?,?) where id=?");
			String sql="select oldSrc,localSrc,artiId,type from d_images where artiId is null";
			System.setOut(new PrintStream(new FileOutputStream("E:/高绪国/资料/images/sql1.sql")));
			ResultSet rs = statement.executeQuery(sql);
			while (rs.next()) {
				int id = rs.getInt("artiId");
				int type = rs.getInt("type");
				String oldSrc = rs.getString("oldSrc");
				String localSrc = rs.getString("localSrc");

				// 遍历处理sql语句
				try {
					if(type == 0) {
						System.out.println("update d_article_grap set content=replace(content,'"+oldSrc+"','"+localSrc+"') where id="+id);
//						updateSt.setString(1, oldSrc);
//						updateSt.setString(2, localSrc);
//						updateSt.setInt(3, id);
//						updateSt.execute();
						i++;
					} else {
						System.out.println("update d_article_grap set thumb=replace(thumb,'"+oldSrc+"','"+localSrc+"') where id="+id);
//						updateThumbSt.setString(1, oldSrc);
//						updateThumbSt.setString(2, localSrc);
//						updateThumbSt.setInt(3, id);
//						updateThumbSt.execute();
						i++;
					}
				} catch(Exception e) {
					e.printStackTrace();
				}
			}
			rs.close();
			updateSt.close();
			statement.close();
			DbUtil.closeConn();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 从内容页面获取缩略图
	 */
	public static void handlThumbImgs() {
		try {
			Connection connection = DbUtil.getQgshConn();
			Statement statement = connection.createStatement();
			PreparedStatement updateSt = connection.prepareStatement("update d_article_grap set thumb=? where id=?");
			String sql="select id,content from d_article_grap where thumb is null";
			ResultSet rs = statement.executeQuery(sql);
			String mainImg = "";
			while (rs.next()) {
				int id = rs.getInt("id");
				String content = rs.getString("content");
				if(!content.contains("<img")) {
					continue;
				}
				System.out.println(id + ",");
				ArticleTo at = new ArticleTo();
				at = getImgFromContent(content, at, 1.5, 0.5, 100);
				mainImg = at.getMainImg();
				if(null == mainImg || mainImg.length() == 0) continue;
				// 遍历处理sql语句
				try {
					updateSt.setString(1, mainImg);
					updateSt.setInt(2, id);
					updateSt.execute();
				} catch(Exception e) {
					e.printStackTrace();
				}
			}
			rs.close();
			updateSt.close();
			statement.close();
			DbUtil.closeConn();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

	/**
	 * 从内容中提取出符合要求的图片
	 * 改为从图片库里面获取图片记录，根据ID更新缩略图
	 * @param content
	 * @param articleTo
	 * @param pr
	 * @param fluc
	 * @param w
	 * @return
	 */
	private static ArticleTo getImgFromContent(String content, ArticleTo articleTo, double pr, double fluc, int w) {
		// 提取src值
		List<String> imgSrcs = ImageUtil.getImgSrc(content);
		if(imgSrcs.isEmpty()) {
			return articleTo;
		}
		
		
		for(String imgSrc : imgSrcs) {
			if(!imgSrc.startsWith("E:/高绪国/资料/images/qgsh/")) continue;
//			if(!oldImgMap.containsKey(imgSrc)) continue;
//			String localSrc = oldImgMap.get(imgSrc);
			System.out.println("======"+imgSrc);
			String localSrc = imgSrc;
			try {
				double imgPr = getPr(localSrc, articleTo);
		        if(pr > 0 && rangeInDefined(imgPr, pr-fluc, pr+fluc) && articleTo.getImgWidth() >= w) {
		        	articleTo.setMainImg(imgSrc);
		        	break;
		        } else if(articleTo.getImgWidth() >= w){
		        	articleTo.setMainImg(imgSrc);
		        }
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
		}
		return articleTo;
	}
	/**
	 * 判断是否在范围内，在则返回true
	 * @param current	当前数据
	 * @param min 最小
	 * @param max	最大
	 * @return
	 */
	public static boolean rangeInDefined(double current, double min, double max) {
		return Math.max(min, current) == Math.min(current, max);
	}
	

	/**
	 * 获取图片尺寸比率
	 * @param imgSrc
	 * @return
	 * @throws Exception
	 */
	private static double getPr(String imgSrc, ArticleTo articleTo) throws Exception {
		// 替换URL，从本地获取图片
//		imgSrc = imgSrc.replace("http://www.wine22.com/images/", localImgDir).replace("http://www.g2room.com/images/", localImgDir);
		File f = new File(imgSrc);
		System.out.println("本地图片："+imgSrc);
		double pr = 0;
	    try {
	    	BufferedImage sourceImg =ImageIO.read(new FileInputStream(f));
	    	if(null != sourceImg) {
	    		articleTo.setImgWidth(sourceImg.getWidth());
	    		pr = Double.valueOf(articleTo.getImgWidth()) / sourceImg.getHeight();
	    	}
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
        return pr;
	}
	/**
	 * 获取所有图片的content里面的地址
	 * @return
	 */
	public static Map<String, String> getOldImgs() {
		Map<String, String> map = new HashMap<String, String>();
		try {
			Connection connection = DbUtil.getQgshConn();
			Statement statement = connection.createStatement();
			String sql="select id,oldSrc,localSrc from d_images where type=0";
			ResultSet rs = statement.executeQuery(sql);
			while (rs.next()) {
				map.put(rs.getString("oldSrc"), rs.getString("localSrc"));
			}
			rs.close();
			statement.close();
			DbUtil.closeConn();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}
	
	/**
	 * 处理之前的updateSql到images表
	 */
	public static void handlImgs() {
		try {
			Connection connection = DbUtil.getQgshConn();
			Statement statement = connection.createStatement();
			PreparedStatement updateSt = connection.prepareStatement("insert into d_images(oldSrc, localSrc,type) values(?,?,?)");
			String sql="select id,updateSql from d_images_update";
			ResultSet rs = statement.executeQuery(sql);
			while (rs.next()) {
				String updateSqlStr = rs.getString("updateSql");
				//update d_article_grap set content=replace(content,'/uploadfile/201.jpg','E:/高绪国/资料/images/qgsh/sourceImg/20160509/nrj/4076850672531dM4qXJ.jpg');
				String oldSrc = updateSqlStr.substring(updateSqlStr.indexOf("'") + 1, updateSqlStr.indexOf("','"));
				String localSrc = updateSqlStr.substring(updateSqlStr.indexOf("','")+3, updateSqlStr.lastIndexOf("'"));
				// 遍历处理sql语句
				try {
					updateSt.setString(1, oldSrc);
					updateSt.setString(2, localSrc);
					updateSt.setInt(3, 0);
					updateSt.execute();
				} catch(Exception e) {
					e.printStackTrace();
				}
			}
			rs.close();
			updateSt.close();
			statement.close();
			DbUtil.closeConn();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
